import 'package:flutter/material.dart';
import 'package:sweet_app/bloc/application_bloc.dart';
import 'package:sweet_app/bloc/bloc_provider.dart';
import 'package:sweet_app/buttons/simple_round_button.dart';
import 'package:sweet_app/http/api.dart';
import 'package:sweet_app/model/user.dart';
import 'package:sweet_app/utils/utils.dart';

class RegisterPage extends StatefulWidget {
  @override
  _RegisterPageState createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  final scaffoldKey = GlobalKey<ScaffoldState>();
  final formKey = GlobalKey<FormState>();
  bool _flag = false;
  String _phone;
  String _password;
  String _name;

  @override
  Widget build(BuildContext context) {
    final ApplicationBloc appBloc = BlocProvider.of<ApplicationBloc>(context);
    return Scaffold(
        appBar: AppBar(
          title: const Text("注册账号"),
          leading: IconButton(
              icon: Icon(Icons.arrow_back),
              onPressed: () {
                appBloc.addEvent(AppEvent.login);
              }),
        ),
        key: scaffoldKey,
        body: SingleChildScrollView(
            child: Padding(
                padding: EdgeInsets.all(16.0),
                child: Form(
                  key: formKey,
                  autovalidate: _flag,
                  child: Column(
                    children: [
                      TextFormField(
                        decoration: InputDecoration(
                            labelText: '昵称', border: OutlineInputBorder()),
                        validator: (val) => val.isEmpty
                            ? "请输入昵称"
                            : val.length > 10 ? "昵称不能超过10个字符" : null,
                        onSaved: (val) => _name = val,
                      ),
                      const SizedBox(height: 10.0),
                      TextFormField(
                        decoration: InputDecoration(
                            labelText: '手机号', border: OutlineInputBorder()),
                        validator: (val) =>
                            val.length != 11 ? '请输入正确的手机号' : null,
                        onSaved: (val) => _phone = val,
                        keyboardType: TextInputType.phone,
                      ),
                      const SizedBox(height: 10.0),
                      TextFormField(
                        decoration: InputDecoration(
                            labelText: '密 码', border: OutlineInputBorder()),
                        validator: (val) => val.length < 6 ? '密码太短' : null,
                        onSaved: (val) => _password = val,
                        obscureText: true,
                      ),
                      const SizedBox(height: 10.0),
                      SimpleRoundButton(
                        onPressed: () => _register(appBloc),
                        backgroundColor: Colors.blueAccent,
                        buttonText: Text(
                          "提 交",
                          style: TextStyle(color: Colors.white),
                        ),
                        textColor: Colors.white,
                      ),
                    ],
                  ),
                ))));
  }

  void _register(appBloc) {
    if (!_flag) {
      setState(() {
        _flag = true;
      });
    }
    final form = formKey.currentState;

    if (form.validate()) {
      form.save();
      _performLogin(appBloc);
    }
  }

  void _performLogin(ApplicationBloc appBloc) async {
    final snackbar = SnackBar(
      content: Text('name: $_name, Phone: $_phone, password: $_password'),
    );

    scaffoldKey.currentState.showSnackBar(snackbar);
    final resultModel =
        await Api.register(phone: _phone, name: _name, password: _password);
    if (resultModel.type == ResultType.success) {
      final user = User.fromJson(resultModel.data['user']);
      print("user: $user");
      final token = resultModel.data['token'];
      print('token: $token');
      await appBloc.saveUserInfo(user, token);
      appBloc.addEvent(AppEvent.home);
    } else {
      showModel(context, resultModel.error);
    }
  }
}
